/**
 * 
 */
package com.caoxw.Android.CityBus;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * @author caoxw
 *
 */
public final class BusScan implements Runnable{
	static final int 			SCAN_BUS = 0;
	static final int 			SCAN_STATION = 1;
	private		boolean			m_bolCancel = false;
	
	public int 					m_intMaxChangeTimes = 3;
	private	long				m_StartTime;
	
	public int					m_TimeOut = 10;
	
	private Context 			m_context = null;
	private FileData 			m_objFd  = null;
	private	int[]				m_StationIndex;
	private	int[]				m_BusIndex;
	private int					m_BusCount = 0;
	private	int					m_StationCount = 0;
	public String				Version;
	public	String				DataName;
	private	String				m_strFileName;
	public String 				CreateTime;
	private boolean				m_isInited = false;
	private LinesStruct 		m_objLBS = new LinesStruct();
	private ArrayList<String> 	m_LastStringResult = null;
	private String				m_KeyWords = "";
	
	private Thread				m_objThread = null;
	
	public String	StationA	=	null;
	public String	StationB	=	null;
	
	public final static int MSG_BUSCAN_INITEING = 1;
	public final static int MSG_BUSCAN_INITED = 2;
	public final static int MSG_BUSCAN_SEARCHING_STR = 3;
	public final static int MSG_BUSCAN_SEARCHING_FINISHED = 4;
	public final static int MSG_BUSCAN_SEARCHLINES_START = 5;
	public final static int MSG_BUSCAN_SEARCHLINES_PROCESSING = 6;
	public final static int MSG_BUSCAN_SEARCHLINES_FINISED = 7;
	public final static int MSG_BUSCAN_ERROR = 10;
	
	private final static int METHOD_SEARCH_STR = 0;
	private final static int METHOD_SEARCH_LINES = 1;
	public  int	 m_Method = 0;
	public final  static int MEARCH_MODE_ASYNC = 1;
	public int SearchMode = MEARCH_MODE_ASYNC;
	
	private Handler	m_handler = null;
	
	public void setHandler(Handler handler){
		m_handler = handler;
	}
	
	public  BusScan(Context context,String FilePath){
		m_StationIndex = new int[38];
		m_BusIndex 	   = new int[38];
		m_context = context;
		m_strFileName = FilePath;
	
	}
	public boolean isInited(){
		return m_isInited;
	}
	public String	getFileName(){
		return m_strFileName;
	}
	public LinesStruct GetChangBusLines(){
		return m_objLBS;
	}
	public void PutChangBusLines(LinesStruct lbs){
		 m_objLBS = lbs;
	}
	public int	GetBusesCount(){
		return m_BusCount;
	}
	public int	GetStationsCount(){
		return m_StationCount;
	}
	/**
	BOOL CBusScan::ReadHerder(CString sDataPath)
	{
		if(!objfs.Load(sDataPath)) return FALSE;
		objfs.SetPosition(0);
		BYTE tembyte[4];
		VersionOffset = 0;
		//读取线路数和站点总数
		objfs.SetPosition(4);
		objfs.Read(tembyte, 0, 4);
		BusCount = tembyte[0]*256+tembyte[1];
		StationCount= tembyte[2]*256+tembyte[3];

		objfs.SetPosition(8);//索引开始
		for (int i = 0; i < 38; i++)
		{
			objfs.Read(tembyte, 0, 4);
			StationIndex[i] = byteTolong(tembyte);
		}

		for (int i = 0; i < 38; i++)
		{
			objfs.Read(tembyte, 0, 4);
			BusIndex[i] = byteTolong(tembyte);
		}
		strVersion =GetStr(VersionOffset,FALSE);
		strDataName=GetStr();
		strCreateTime=GetStr();
		return TRUE;

	}
	*/
	public void Cancel(){
		m_bolCancel = true;
	}
	public boolean isCancel(){
		return m_bolCancel;
	}
	public boolean readHeader(){
		return readHeader(m_strFileName);
	}
	public boolean readHeader(String FilePath){
		if("".equals(FilePath)|| !FilePath.endsWith(".cbus"))
			return false;
		m_objFd = new FileData(m_context, FilePath);
		if(!m_objFd.loadData()) return false;
		m_objFd.setPosition(4);
		byte[] tembyte = m_objFd.read(0, 4);
		m_BusCount = (tembyte[0]<0?tembyte[0]+256:tembyte[0])*256+(tembyte[1]<0?tembyte[1]+256:tembyte[1]);
		m_StationCount= (tembyte[2]<0?tembyte[0]+256:tembyte[2])*256+(tembyte[3]<0?tembyte[3]+256:tembyte[3]);
		if(m_BusCount<=0 || m_StationCount<=0) return false;
		m_objFd.setPosition(8);//索引开始
		System.out.println("Start Read Station Index");
		for (int i = 0; i < 38; i++)
		{
			tembyte = m_objFd.read(0, 4);
			m_StationIndex[i] = byteTolong(tembyte);
			if(m_StationIndex[i]<=0) return false;
		}
		System.out.println("Start Read Bus Index");
		for (int i = 0; i < 38; i++)
		{
			tembyte = m_objFd.read(0, 4);
			m_BusIndex[i] = byteTolong(tembyte);
			if(m_BusIndex[i]<=0) return false;
		}
		System.out.println("Start Read Versio  Index");
		Version =GetStr(0,false);
		if(Version.length()==0) return false;
		System.out.println("Start Read DataName  Index");
		DataName=GetStr();
		System.out.println("Start Read CreateTime  Index");
		CreateTime=GetStr();
		m_isInited = true;
		System.out.println("Init  ReadHeader");
		return true;
	}
	
	public int byteTolong(byte[] Byte)
	{
		int[] data =new int[4];
		for(int i=0;i<4;i++)
			data[i] = (Byte[i]<0) ? 256+Byte[i] : Byte[i];
			//Byte[i] = (byte) ((Byte[i]<0) ? 256+Byte[i] : Byte[i]);
		 return data[0] * 256 * 256 * 256 + data[1] * 256 * 256 + data[2] * 256 + data[3];
	}

	
	/**
	 * 
	 * @param String Station 站点名称
	 * @return ArrayList<String> 线路列表
	 */
	public ArrayList<String> GetBusesListByStation(String Station){
		return ScanString(Station,false);
	}
	/**
	 * 
	 * @param String Station 站点名称
	 * @return ArrayList<String> 线路列表
	 */
	public ArrayList<String> GetStationsListByBus(String BusName){
		//ArrayList<String> ResultList = ScanString(BusName);//new ArrayList<String>();
		/**
		ResultList.add(BusName);
		ResultList.add(CnToSpell.getFirstSpell(BusName));
		ResultList.add(new String("测试站点1"));
		ResultList.add(new String("测试站点2"));
		ResultList.add(new String("测试站点3"));
		ResultList.add(new String("测试站点4"));
		*/
		return ScanString(BusName,true);
	}
	
	
	public String GetStr()
	{
		return GetStr(-1,false);
	}
	//class 1:线路   2：站点
	private int GetIndexData(int Index,boolean isStation)
	{
		if(!isStation)
			return m_BusIndex[Index];
		else
			return m_StationIndex[Index];
	}
	private int GetDataOffset(String KeyWords,boolean isStation)
	{
		byte[] tembyte = new byte[4];
		int IndexNo = GetIndexNo(KeyWords);
		int startOffset = GetIndexData(IndexNo,isStation);
		int EndOffset = GetIndexData(IndexNo+1,isStation);
		m_objFd.setPosition (startOffset);
		String temStr = null;
		int temPos;
		while (m_objFd.getPosition() < EndOffset)
		{
			temPos=m_objFd.getPosition();
			temStr = GetStr(temPos,true);//.trim();
			//Log.d("GetDataOffset:",temStr + "  " + KeyWords);
			if (KeyWords.equals(temStr))
			{
				m_objFd.setPosition(temPos+4);
				tembyte = m_objFd.read(0, 4);
				return byteTolong(tembyte);
			}
			else
			{
				m_objFd.setPosition (temPos+ 8);
			}
		}

		return 0;
	}
	
	public  BusInfo getBusInfo(String BusName){
		BusInfo objBus = null;
	    String time1, time2, time3, time4;
		int hour,min;
	    int stationCount1, stationCount2;
	    int busInfoOffset = GetDataOffset(BusName,false);
	    int lngTempOffset;
	   
		//BusIn.strOtherInfo=_T("");
		//BusIn.strTime1=_T("");
		//BusIn.strTime2=_T("");
		//BusIn.strTime3=_T("");
		//BusIn.strTime4=_T("");
	    byte[] tembyte = new byte[4];
	    if (busInfoOffset == 0)
	    {
			return null;
	    }
	    else
	    {
	    	objBus = new BusInfo();
	    	objBus.m_BackStations = new ArrayList<String>();
	 	    objBus.m_GoStations   =  new ArrayList<String>();
	 	    objBus.m_BusName = BusName;

	    	m_objFd.setPosition(busInfoOffset);
	        //objfs.Position = 15400;
			hour = m_objFd.ReadByte();
			min = m_objFd.ReadByte();
			time1 = String.format("%02d:%02d", hour, min);

			hour=m_objFd.ReadByte();
			min=m_objFd.ReadByte();
	        time2 = String.format("%02d:%02d", hour, min);

			hour=m_objFd.ReadByte();
			min=m_objFd.ReadByte();
	        time3 = String.format("%02d:%02d", hour, min);

			hour=m_objFd.ReadByte();
			min=m_objFd.ReadByte();
	        time4 = String.format("%02d:%02d", hour, min);

			//objfs.Read(tembyte, 0, 4);
			stationCount1 = m_objFd.ReadByte();
			stationCount2 = m_objFd.ReadByte();


			objBus.m_Time1 = time1 + "--" +time2;
			objBus.m_Time2 = time3 + "--" +time4;
	        

	        for (int i = 0; i < stationCount1; i++)
	        {
	        	tembyte = m_objFd.read(0, 4);
				lngTempOffset=m_objFd.getPosition();
				objBus.m_GoStations.add(GetStr(byteTolong(tembyte)));
				m_objFd.setPosition(lngTempOffset);
	        }
			
	        for (int i = 0; i < stationCount2; i++)
	        {
	        	tembyte = m_objFd.read(0, 4);
	        	lngTempOffset=m_objFd.getPosition();
	        	objBus.m_BackStations.add(GetStr(byteTolong(tembyte)));
				m_objFd.setPosition(lngTempOffset);
	        }
			//Info(L"早班时间："+pMainFram->BusInfo.strTime1+L"\r\n末班时间："+pMainFram->BusInfo.strTime2);
	        objBus.m_OtherInfo ="早班时间：" + objBus.m_Time1 + "\n末班时间：" + objBus.m_Time1;
			//return TRUE;

	    }
		return objBus;
		
	}
	/**
	 * 
	 */
	public  ArrayList<String> getStationInfo(String stationName)
	{
		ArrayList<String> Result = new ArrayList<String>();
		if(!m_isInited) return Result;
	    String temStr = null;
	    byte[] tembyte = new byte[4];
		int intBusStatus;
		int stationInfoOffset = GetDataOffset(stationName,true);
		if(stationInfoOffset==0) return Result;
		m_objFd.setPosition ( stationInfoOffset);
		tembyte = m_objFd.read(0, 4);
	    while (byteTolong(tembyte) != 0)
	    {
			intBusStatus = m_objFd.ReadByte();
			stationInfoOffset = m_objFd.getPosition();
	        temStr=GetStr(byteTolong(tembyte),true);
			Result.add(temStr);
			m_objFd.setPosition(stationInfoOffset);
			tembyte = m_objFd.read(0, 4);
	    }
	    return Result;
	}
	public String GetStr(int Position){
		return GetStr(Position,true);
	}
	public String GetStr(int Position,boolean Back)
	{
		byte lowC = 0;
		byte[] arrBytes;
		int ReadCount=0;
		int oldPosition=m_objFd.getPosition();
		int lStartPosition = oldPosition;
		if(Position>=0){
			m_objFd.setPosition(Position);
			lStartPosition = byteTolong(m_objFd.read(0,4));
			m_objFd.setPosition(lStartPosition);
		}
		if(lStartPosition<=0) return "";
		while (true)
		{
			lowC = m_objFd.ReadByte();

			if (lowC == 0 )break;
			if (lowC > 127 || lowC < 0) m_objFd.ReadByte();
		}
		ReadCount=m_objFd.getPosition()-lStartPosition;
		arrBytes=new byte[ReadCount];
		m_objFd.setPosition(lStartPosition);
		arrBytes = m_objFd.read(0,ReadCount);
		String rtStr;
		try {
			rtStr = new String(arrBytes,"gbk");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			rtStr = new String(arrBytes);
		}
		if(Back) m_objFd.setPosition(oldPosition);
		return rtStr.trim();
	}
	
	/**
	 * 取得拼音首字母
	 * @param str
	 * @return
	 */
	public char GetFirstPyAlpha(String str)
	{
		String Spell = CnToSpell.getFirstSpell(str);
		if(Spell.length()==0) return '}';
		return Spell.charAt(0);
	}
	/**
	 * 在给出的索引区间内查找字符串
	 * @param KeyWords    关键字
	 * @param StartIndex  开始索引
	 * @param EndIndex    结束索引
	 * @param ScanStation 站点查询
	 * @return ArrayList<String>
	 */
	public ArrayList<String> ScanInIndexSpan(String KeyWords,int StartIndex,int EndIndex,boolean ScanStation)
	{
		int startOffset;
		int EndOffset ;
		String temStr = "";
		ArrayList<String> ResultList = new ArrayList<String>();
	    if(ScanStation)
		{
			startOffset = m_StationIndex[StartIndex];
			EndOffset = m_StationIndex[EndIndex];
		}else
		{
			startOffset = m_BusIndex[StartIndex];
			EndOffset = m_BusIndex[EndIndex];
		}

		int temPos=startOffset;
		if(temPos==0) return ResultList;
		m_objFd.setPosition(startOffset);
	    while (m_objFd.getPosition() < EndOffset)
	    {
			temPos= m_objFd.getPosition();
			temStr = GetStr(temPos,true);
			Log.d(KeyWords,temStr);
			if (temStr.startsWith(KeyWords))
					ResultList.add(temStr);
			m_objFd.setPosition(temPos + 8);
	    }
	    return ResultList;
	}
	
	@SuppressWarnings("unchecked")
	public ArrayList<String> ScanString(String KeyWords,boolean ScanStation)
	{
		int IndexNo=0;
		ArrayList<String> ResultList = new ArrayList<String>();
		if(m_LastStringResult == null) m_LastStringResult = new ArrayList<String>();
		if(KeyWords.startsWith(m_KeyWords) && m_LastStringResult.size()>0)
		{
			for(int i=0;i<m_LastStringResult.size();i++)
			{
				if(m_LastStringResult.get(i).startsWith(KeyWords))
					ResultList.add(m_LastStringResult.get(i));
			}
			
		}
		else
		{
			IndexNo=GetIndexNo(KeyWords);
			System.out.println(IndexNo);
			if(IndexNo<0) return ResultList;
			ResultList = ScanInIndexSpan(KeyWords,IndexNo,IndexNo+1,ScanStation);

		}
		m_LastStringResult.clear();
		m_LastStringResult = (ArrayList<String>)ResultList.clone();
		m_KeyWords = KeyWords;
		return ResultList;
	}
	/**
	 * 跳过字符串
	 * @param Position
	 * @return
	 */
	private long JumpStr(int Position)
	{
		byte lowC = 0;
		m_objFd.setPosition(Position);
		while (true)
		{
			lowC = m_objFd.ReadByte();

			if (lowC == 0)break;
			if (lowC > 127|| lowC < 0) m_objFd.ReadByte();
		}
		return m_objFd.getPosition()-Position;
	}
	
	/**
	 * 获取索引号
	 */
	public int  GetIndexNo(String KeyWords)
	{
		char p=GetFirstPyAlpha(KeyWords);
		if(p>='a' && p<='z' )
			return p-'a';
		else if(p=='{' )
			return 26;
		else if(p>='0' && p<='9')
			return p-'0'+27;	
		else if(p=='?' )
			return 37;
		return -1;
	}
	
	public LinesStruct SearchLines(String strStationNameA,String strStationNameB){
		sendMsg(MSG_BUSCAN_SEARCHLINES_START);
		return SearchLines(strStationNameA,strStationNameB,SearchMode==BusScan.MEARCH_MODE_ASYNC);
	}
	private LinesStruct SearchLines(String strStationNameA,String strStationNameB,boolean isAsync)
	{
		m_bolCancel = false;
		sendMsg(MSG_BUSCAN_SEARCHLINES_PROCESSING);
		m_StartTime = System.currentTimeMillis();
		//sendMsg(MSG_BUSCAN_SEARCHLINES_PROCESSING);
		StationA = strStationNameA;
		StationB = strStationNameB;
		LinesStruct LBS = new LinesStruct();
		if(isAsync == true){
			this.m_Method = METHOD_SEARCH_LINES;
			if(m_objThread!=null) m_objThread.stop();
			m_objThread = new Thread(this);
			m_objThread.start();
			//this.getState() == Thread.State.
			//this.start();
			return LBS;
		}
		int changeTime=0;
		int StationANameOffset = GetStringOffset(strStationNameA,true);//名字字符串所在地址
		int StationBNameOffset = GetStringOffset(strStationNameB,true);//名字字符串所在地址
		if(StationANameOffset<=0 || StationBNameOffset<=0) return LBS;
		LBS = SearchLines(StationANameOffset,StationBNameOffset);
		while(changeTime < m_intMaxChangeTimes && LBS.m_CBS.size()==0)
		{
			sendMsg(MSG_BUSCAN_SEARCHLINES_PROCESSING,changeTime+1);
			LBS = SearchChangeAnyTimes(StationANameOffset, StationBNameOffset,++changeTime);
		}
		m_objLBS = LBS;
		sendMsg(MSG_BUSCAN_SEARCHLINES_FINISED,0,0,LBS);
		return LBS;
	}
	//供换乘查找调用
	private LinesStruct SearchLines(int StationANameOffset,int StationBNameOffset)
	{
		LinesStruct LBS = new LinesStruct();
		if(m_TimeOut>0 &&  System.currentTimeMillis()-m_StartTime > m_TimeOut*1000  || m_bolCancel)
		{
			return LBS;
		}	
		int StationAOffset = GetDataOffset(StationANameOffset);//返回A站数据区地址
		if(StationAOffset<=0) return LBS;
		int temOffset;
		int BusNameOffset;
	    byte[] tembyte = new byte[4];
		int intBusStatus,intStationsCount,intTempStatus;
		m_objFd.setPosition(StationAOffset);
		tembyte = m_objFd.read(0, 4);
	    while (byteTolong(tembyte) != 0 &&  !m_bolCancel)
	    {
			intBusStatus = m_objFd.ReadByte();//读取车的状态
			temOffset= m_objFd.getPosition();//存储当前指针
	        BusNameOffset=byteTolong(tembyte);//得到字符串地址
			//下面的函数会让指针位置发生变化
			if(intBusStatus==3)
			{
				intTempStatus=1;
				intStationsCount = GetStationsBetween(StationANameOffset,StationBNameOffset,BusNameOffset,intTempStatus);
				if(intStationsCount>0)
				{
					ChangeBus CBS = new ChangeBus();
					CBS.TotalStations = intStationsCount;
					CBS.intStatus.add(intTempStatus);
					CBS.Buses.add(BusNameOffset);
					CBS.Stations.add(StationANameOffset);
					CBS.StationsCount.add(intStationsCount);
					LBS.Add(CBS);
				}
				//else
					//ErrorBus.Add(BusNameOffset,intTempStatus);
				intTempStatus=2;
				intStationsCount = GetStationsBetween(StationANameOffset,StationBNameOffset,BusNameOffset,intTempStatus);
				if(intStationsCount>0)
				{
					ChangeBus CBS = new ChangeBus();
					CBS.TotalStations = intStationsCount;
					CBS.intStatus.add(intTempStatus);
					CBS.Buses.add(BusNameOffset);
					CBS.Stations.add(StationANameOffset);
					CBS.StationsCount.add(intStationsCount);
					LBS.Add(CBS);
				}
				//else
					//ErrorBus.Add(BusNameOffset,intTempStatus);
			}
			else 
			{
				
				intStationsCount = GetStationsBetween(StationANameOffset,StationBNameOffset,BusNameOffset,intBusStatus);
				if(intStationsCount>0)
				{
					ChangeBus CBS = new ChangeBus();
					CBS.TotalStations =intStationsCount;
					CBS.intStatus.add(intBusStatus);
					CBS.Buses.add(BusNameOffset);
					CBS.Stations.add(StationANameOffset);
					CBS.StationsCount.add(intStationsCount);
					LBS.Add(CBS);
				}
				//else
					//ErrorBus.Add(BusNameOffset,intTempStatus);
			}
			m_objFd.setPosition(temOffset);//还原指针位置
			tembyte = m_objFd.read( 0, 4);//读取下一个车数据
	    }
	    return LBS;

	}
	
	private int GetDataOffset(int StringOffset){
	    byte[] tembyte = new byte[4];
	    m_objFd.setPosition (StringOffset+4);
	    tembyte =m_objFd.read(0, 4);
	   return byteTolong(tembyte);

	}

	//同一线上两站之间相距多少站   单向
	private int GetStationsBetween(int StationANameOffset,int StationBNameOffset,int BusNameOffset,int intStatus){
		byte[] tembyte =  new byte[4];
		int StationCount=0;
		boolean FoundStationA = false;
		int BusOffset = GetDataOffset(BusNameOffset);
		int intGoStationsCount,intBackStationsCount;
		m_objFd.setPosition(BusOffset+8);//跳过时间数据区（八字节）
		intGoStationsCount=m_objFd.ReadByte();
		intBackStationsCount=m_objFd.ReadByte();
		//在去行中查找
		if(intStatus==1){
			for(int i=0;i<intGoStationsCount;i++){
				tembyte = m_objFd.read(0, 4);
				if(byteTolong(tembyte)==StationANameOffset){
					FoundStationA = true;
					StationCount=0;
					continue;
				}
				if(FoundStationA) StationCount++;

				if(byteTolong(tembyte)==StationBNameOffset&&FoundStationA){
					return StationCount;
				}	
			}
		}else if(intStatus==2){//在回行中查找
			StationCount=0;
			FoundStationA = false;
			//跳到回行数据区
			m_objFd.setPosition(BusOffset+8+2+intGoStationsCount*4);
			for(int i=0;i<intBackStationsCount;i++){
				tembyte =m_objFd.read(0, 4);
				if(byteTolong(tembyte)==StationANameOffset){
					FoundStationA=true;
					StationCount=0;
					continue;
				}
				if(FoundStationA) StationCount++;

				if(byteTolong(tembyte)==StationBNameOffset&&FoundStationA){
					return StationCount;
				}
			}
		}
		return 0;
	}

	//返回站点名所在的地址
	int GetStringOffset(String KeyWords,boolean isStation)
	{
		int temPos;
		int IndexNo=GetIndexNo(KeyWords);
		int startOffset = isStation ? m_StationIndex[IndexNo]:m_BusIndex[IndexNo];
		int EndOffset = isStation ? m_StationIndex[IndexNo+1]:m_BusIndex[IndexNo];
		m_objFd.setPosition(startOffset);
	    String temStr ="";

	    while (m_objFd.getPosition() < EndOffset)
	    {
			temPos=m_objFd.getPosition();
	        temStr = GetStr(temPos);
			
	        if (KeyWords.equals(temStr))
	            return temPos;
	        else
	        	m_objFd.setPosition(temPos+ 8);
	    }
	    return 0;
	}

	public int GetStationsBetween(String strStationNameA,String strStationNameB,String strBusName,int intStatus)
	{
		ArrayList<String> strArray = new ArrayList<String>();
		int StationANameOffset = GetStringOffset(strStationNameA,true);//名字字符串所在地址
		int StationBNameOffset = GetStringOffset(strStationNameB,true);//名字字符串所在地址
		byte[] tembyte=new byte[4];
		int StationCount=0;
		boolean FoundStationA = false;
		int BusOffset = GetDataOffset(strBusName,false);
		int temOffset;
		int intGoStationsCount,intBackStationsCount;
		m_objFd.setPosition(BusOffset+8);//跳过时间数据区（八字节）
		intGoStationsCount= m_objFd.ReadByte();
		intBackStationsCount= m_objFd.ReadByte();
		strArray.clear();
		//在去行中查找
		if(intStatus==1)
		{
			for(int i=0;i<intGoStationsCount;i++)
			{
				tembyte = m_objFd.read( 0, 4);
				temOffset= m_objFd.getPosition();
				if(byteTolong(tembyte)==StationANameOffset)
				{
					FoundStationA=true;
					StationCount=0;
					strArray.clear();
					continue;
				}
				if(FoundStationA) 
				{
					StationCount++;
					strArray.add(GetStr(byteTolong(tembyte)));
				}

				if(byteTolong(tembyte)==StationBNameOffset&&FoundStationA)
				{
					return StationCount;
				}	
				m_objFd.setPosition(temOffset);
			}
		}
		else if(intStatus==2)//在回行中查找
		{
			StationCount=0;
			FoundStationA=false;
			//跳到回行数据区
			m_objFd.setPosition(BusOffset+8+2+intGoStationsCount*4);
			for(int i=0;i<intBackStationsCount;i++)
			{
				tembyte = m_objFd.read(0, 4);
				temOffset=m_objFd.getPosition();
				if(byteTolong(tembyte)==StationANameOffset)
				{
					FoundStationA = true;
					StationCount=0;
					strArray.clear();
					continue;
				}
				if(FoundStationA)
				{
					StationCount++;
					strArray.add(GetStr(byteTolong(tembyte)));
				}

				if(byteTolong(tembyte)==StationBNameOffset&&FoundStationA)
				{
					return StationCount;
				}
				m_objFd.setPosition(temOffset);
			}
		}
		strArray.clear();
		return 0;
	}

	private LinesStruct SearchChangeAnyTimes(int StationANameOffset,int StationBNameOffset,int nDeep)
	{
		LinesStruct LBS = new  LinesStruct();
		if(m_TimeOut>0 && System.currentTimeMillis()-m_StartTime > m_TimeOut*1000 || m_bolCancel)
		{
			//System.out.println("查找超时，正在返回...");
			sendMsg(MSG_BUSCAN_ERROR,0,0,"查询超时...");
			return LBS;
		}
		LinesStruct LBS2 = new LinesStruct();
		int StationAOffset = GetDataOffset(StationANameOffset);//返回A站数据区地址
		int temOffset,temOffset2;
		int BusNameOffset,MidStationNameOffset;
		boolean FoundStationA;
		int intGoStationsCount,intBackStationsCount;
	    byte[]  tembyte = new byte[4];
		int intBusStatus,intCurrentBusStatus,intStationsCount;
		m_objFd.setPosition(StationAOffset);
		tembyte = m_objFd.read( 0, 4);
		//找到经过站点A的所有线路
	    while (byteTolong(tembyte) != 0 &&  !m_bolCancel)
	    {
			intBusStatus = m_objFd.ReadByte();//读取线路的状态
	        BusNameOffset=byteTolong(tembyte);//得到字符串地址
			temOffset=	m_objFd.getPosition();
			m_objFd.setPosition (GetDataOffset(BusNameOffset)+8);//跳过时间数据区（八字节）
			intGoStationsCount=m_objFd.ReadByte();
			intBackStationsCount=m_objFd.ReadByte();
			if(intBusStatus!=2)
			{
				FoundStationA = false;
				intStationsCount=0;
				intCurrentBusStatus=1;
				for(int i=0;i<intGoStationsCount;i++) //此线路所经过的站点
				{
					tembyte = m_objFd.read( 0, 4);
					MidStationNameOffset = byteTolong(tembyte);
					temOffset2=m_objFd.getPosition();//存储当前指针
					if(MidStationNameOffset==StationANameOffset)
					{
						FoundStationA=true;
						intStationsCount=0;
						continue;
					}
					if(FoundStationA) //通过A站
					{
						intStationsCount++;
						if(nDeep>1)
							LBS2 = SearchChangeAnyTimes(MidStationNameOffset,StationBNameOffset,nDeep-1);
						else 
							LBS2 = SearchLines(MidStationNameOffset,StationBNameOffset);
						if(!LBS2.isEmpty())
						{
							for(int j=0;j<LBS2.size();j++)
							{
								ChangeBus CBS = new ChangeBus();
								CBS.TotalStations = intStationsCount;
								CBS.Buses.add(BusNameOffset);
								CBS.intStatus.add(intCurrentBusStatus);
								CBS.Stations.add(StationANameOffset);
								CBS.StationsCount.add(intStationsCount);
								CBS.Add(LBS2.get(j));
								LBS.Add(CBS);
							}
						}
					}
					m_objFd.setPosition(temOffset2);//还原指针位置
				}
			}
			if(intBusStatus!=1)
			{
				FoundStationA=false;
				intStationsCount=0;
				intCurrentBusStatus=2;
				for(int i=0;i<intBackStationsCount;i++)
				{
					tembyte = m_objFd.read( 0, 4);
					MidStationNameOffset=byteTolong(tembyte);
					temOffset2=m_objFd.getPosition();//存储当前指针
					if(MidStationNameOffset==StationANameOffset)
					{
						FoundStationA=true;
						intStationsCount=0;
						continue;
					}
					if(FoundStationA)
					{	
						intStationsCount++;
						if(nDeep>1)
							LBS2 = SearchChangeAnyTimes(MidStationNameOffset,StationBNameOffset,nDeep-1);
						else 
							LBS2 = SearchLines(MidStationNameOffset,StationBNameOffset);

						if(!LBS2.isEmpty())
						{
							for(int j=0;j<LBS2.size();j++)
							{
								ChangeBus CBS = new ChangeBus();
								CBS.TotalStations = intStationsCount;
								CBS.Buses.add(BusNameOffset);
								CBS.intStatus.add(intCurrentBusStatus);
								CBS.Stations.add(StationANameOffset);
								CBS.StationsCount.add(intStationsCount);
								CBS.Add(LBS2.get(j));
								LBS.Add(CBS);
							}	
						}
					}
					
					m_objFd.setPosition(temOffset2);//还原指针位置
				}
			}
			m_objFd.setPosition ( temOffset);//还原指针位置
			tembyte = m_objFd.read( 0, 4);//读取下一个车数据
	    }
		return LBS;
	}
	
	public String getDataName(String fileName){
		try {
			FileInputStream  fis = m_context.openFileInput(fileName);
			byte[] tembyte = new byte[4];
			fis.read(tembyte);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
		
	}
	private void sendMsg(int flag,int arg1) {
		sendMsg(flag,arg1,0,null);
	}
	private void sendMsg(int flag) {
		sendMsg(flag,0,0,null);
	}
	private void sendMsg(int flag,int arg1,int arg2,Object object) {
		Message msg = new Message();
		msg.arg1 = arg1;
		msg.arg2 = arg2;
		msg.what = flag;
		msg.obj = object;
		m_handler.sendMessage(msg);
	}
	public void run() {
		// TODO Auto-generated method stub
		switch(m_Method){
		case METHOD_SEARCH_LINES:
			SearchLines(StationA, StationB,false);
			break;
		}
		
	}

}


